package com.dwk.demo02;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import java.text.SimpleDateFormat;

/**
 * 封装Jackon工具类，用于转化为JSON字符串
 */
public class JsonUtil {
    /**
     * 用于Date类型转换为JSON
     * @param object
     * @return
     */
    public static String getDateJson(Object object,String dateFormat){
        ObjectMapper mapper=new ObjectMapper();
        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);
        //时间格式化
        SimpleDateFormat sdf=new SimpleDateFormat(dateFormat);
        mapper.setDateFormat(sdf);
        try {
            return mapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getDateJson(Object object){
        return getDateJson(object,"yyyy-MM-dd HH:mm:ss");
    }


    public static String getObjectJson(Object object){
        ObjectMapper mapper=new ObjectMapper();
        try {
            return mapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
}